<?php

namespace apiend\modules\inventory\models;

use Yii;
use yii\db\Exception;
use yii\helpers\Json;
use common\helpers\ArrayHelper;
use common\models\rfid\Rfid;
use common\models\inventory\InventoryBatch;
use common\models\inventory\InventoryLog;

/**
 * 盘点模型
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class UploadForm extends \common\base\Model {

    /**
     * @var integer 批次ID
     */
    public $batch_id;

    /**
     * @var string 用户UID
     */
    public $nums;

    /**
     * @var string 用户UID
     */
    public $data;

    /**
     * @var object 票据类型
     */
    private $_model = null;

    /**
     * @var object 票据类型
     */
    private $_rfids = [];

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['data', 'batch_id', 'nums'], 'required'],
            [['batch_id', 'nums'], 'integer'],
            [['batch_id'], 'validateBatch'],
            [['data'], 'validateData'],
        ];
    }

    /**
     * Finds user by [[username]]
     *
     * @return \api\models\UserCompatibleModel|null
     */
    protected function getModel() {
        if ($this->_model === null) {
            $this->_model = InventoryBatch::findOne($this->batch_id);
        }
        return $this->_model;
    }

    protected function getRfids() {
        return $this->_rfids;
    }

    /**
     * 格式化地点
     */
    public function validateBatch($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        if ($this->getModel() == null) {
            $this->addError($attribute, '盘点批次不存在');
        }
    }

    /**
     * 格式化地点
     */
    public function validateData($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $json = base64_decode($this->$attribute);
        $data = Json::decode($json);

        if (count($data) != $this->nums) {
            $this->addError($attribute, $this->nums . '数据不一致' . count($data));
        } else {
            foreach ($data as $item) {
                $this->_rfids[] = [
                    $this->batch_id,
                    $item['sn'],
                    hexdec($item['data']),
                    time()
                ];
            }
        }
    }

    /**
     * 保存动态信息（发布&修改）
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('提交失败');
        }
        $rfids = $this->getRfids();
        if (empty($rfids)) {
            return $this->dumpError('未检测到标签');
        }
        $batch = $this->getModel();
        $queryBuilder = Yii::$app->db->createCommand();
        $attributes = ['batch_id', 'sn', 'data', 'created_at'];
        $amount = $queryBuilder->batchInsert(InventoryLog::tableName(), $attributes, $rfids)->execute();

        if ($amount) {
            $query = InventoryLog::find()->where([
                'batch_id' => $this->batch_id,
                'status' => InventoryLog::STATUS_DEFAULT
            ]);
            foreach ($query->each() as $log) {
                $rfid = Rfid::findBySn($log->sn, $batch->type_id);
                if ($rfid) {
                    $log->rf_id = $rfid->id;
                    $log->bill_id = $rfid->bill_id;
                    $log->status = InventoryLog::STATUS_COMPLETED;
                } else {
                    $log->status = InventoryLog::STATUS_UNDEFIND;
                }
                if (!$log->save()) {
                    return $this->dumpError($log->errors);
                }
            }
            //创建任务队列
//            $taskid = Yii::$app->queue->push(new \common\jobs\InventoryBatchJob([
//                'batch_id' => $this->batch_id,
//            ]));
        }
        Yii::error([
            'amount' => $amount,
            'rfids' => $rfids,
        ]);
        return $amount;
    }

}
